

class nodePoolCell {
    public pool: cc.NodePool;
    public cell: cc.Prefab;
}
class PoolManager {
    private static _instance?: PoolManager;

    public nodePool: { [key: string]: nodePoolCell } = {};

    public viewPool: { [key: string]: cc.Node[] } = {};
    static get inst(): PoolManager {
        if (this._instance == undefined) {
            this._instance = new PoolManager();
        }
        return this._instance;
    }

    public getNode(nodeType: string): cc.Node {
        if (!this.nodePool[nodeType]) {

        }

        if (this.nodePool[nodeType].pool.size() > 0) {
            return this.nodePool[nodeType].pool.get();
        } else {
            return cc.instantiate(this.nodePool[nodeType].cell);
        }

    }

    public createNodePool(nodeType: string, prefab: any, defaultNum?: number): void {
        if (this.nodePool[nodeType]) {
            //AppLog.err(cc.js.formatStr("is already have this pool:%s", nodeType));
            return;
        }

        this.nodePool[nodeType] = new nodePoolCell();
        this.nodePool[nodeType].pool = new cc.NodePool();
        this.nodePool[nodeType].cell = prefab;

        if (defaultNum) {
            for (let index = 0; index < defaultNum; index++) {

                const node: cc.Node = cc.instantiate(prefab);
                this.nodePool[nodeType].pool.put(node);
            }
        }

    }

    public putNode(nodeType: string, node: cc.Node): void {
        if (this.nodePool[nodeType]) {
            node.removeFromParent(false);
            this.nodePool[nodeType].pool.put(node);
        } else {

        }
    }

    public putViewNode(nodeType: string, node: cc.Node): void {
        if (!this.viewPool[nodeType]) {
            this.viewPool[nodeType] = [];

        }
        node.removeFromParent(false);
        this.viewPool[nodeType].push(node);
    }

    public getViewNode(nodeType: string): cc.Node {
        if (!this.viewPool[nodeType]) {
            this.viewPool[nodeType] = [];
            return undefined;
        } else {
            if (this.viewPool[nodeType].length > 0) {

                return this.viewPool[nodeType].pop();
            } else {
                return undefined;
            }
        }
    }
    public clear(): void {
        for (const key in this.nodePool) {
            this.nodePool[key].pool.clear();
        }
        this.nodePool = {};
        this.viewPool = {};
    }

}
const PoolMgr: PoolManager = PoolManager.inst;
export default PoolMgr;
